package com.app.babygo.dbservice;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {

	// database info
	protected static final String DATABASE_NAME = "babygo.db";
	protected static final String DATABASE_TABLE_ACCOUNT = "account";
	protected static final String DATABASE_TABLE_CHILD = "child";
	protected static final String DATABASE_TABLE_ACHIEVEMENT = "achievement";
	protected static final String DATABASE_TABLE_CHILD_ACHIEVEMENT = "child_achievement";
	protected static final DateFormat DB_DATE_FORMAT = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy", Locale.US);
	protected static final int DATABASE_VERSION = 1;
	protected static String TAG = "DBAdapter";
	
	// database instance
	protected final Context context;
	protected DatabaseHelper DBHelper;
	protected SQLiteDatabase db;

	protected static class DatabaseHelper extends SQLiteOpenHelper {

		public DatabaseHelper(Context context) {
			// TODO Auto-generated constructor stub
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			if (!UserAdapter.createTable(db)) {
				//TODO: find a way to notify user
			}
			if (!ChildAdapter.createTable(db)) {
				//TODO: find a way to notify user
			}
			if (!AchievementAdapter.createTable(db)) {
				//TODO: find a way to notify user
			}
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version" + oldVersion + "to "
					+ newVersion + " , will drop old data");
			// TODO: not right way to do, copy the existing info to new table
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_ACCOUNT);
			onCreate(db);
		}
	}

	public DBAdapter(Context ctx) {
		this.context = ctx;
	}

	public DBAdapter open() {
		DBHelper = new DatabaseHelper(context);
		db = DBHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		DBHelper.close();
	}
	
	protected static String getString(Cursor cursor, String columnName){
		int index = cursor.getColumnIndex(columnName);
		return cursor.getString(index);
	}
	
	protected static int getInt(Cursor cursor, String columnName){
		int index = cursor.getColumnIndex(columnName);
		return cursor.getInt(index);
	}
	
	protected static Date getDate(Cursor cursor, String columnName) throws ParseException{
		int index = cursor.getColumnIndex(columnName);
		return DB_DATE_FORMAT.parse(cursor.getString(index));
	}

}
